package com.woyowodaows.utils;

import com.woyowodaows.request.InterfaceUrl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/10.
 */

public class MD5Utils {
    private static MessageDigest md5 = null;

    public static String getMd5(String str)  {
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(str.getBytes());
            StringBuilder sb = new StringBuilder(40);
            for (byte x : bs) {
                if ((x & 0xff) >> 4 == 0) {
                    sb.append("0").append(Integer.toHexString(x & 0xff));
                } else {
                    sb.append(Integer.toHexString(x & 0xff));
                }
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }


    public static String createSign(Map<String, Object> params) {
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        StringBuilder query = new StringBuilder();
        for (String key : keys) {
            if ("sign".equals(key)) {
                continue;
            }

            String value = params.get(key)==null?null:String.valueOf(params.get(key));
            query.append(key).append(value);
        }
        query.append(InterfaceUrl.SECRET);
        return MD5Utils.getMd5(query.toString());
    }



}
